package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreDateUtils;
import com.lehecai.core.util.CoreFetcherUtils;
import com.lehecai.core.util.CoreJSONUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * 彩票百乐门 开奖结果抓取
 * @author Sunshow
 *
 */
public class LotteryDrawFetchWorkerCpblm extends AbstractLotteryDrawFetchWorker {

    private static final Map<LotteryType, String> lotteryTypeMap = new HashMap<LotteryType, String>();

    static {
        lotteryTypeMap.put(LotteryType.SHSSL, "http://zoushitu.cpblm.com/json/ssl/shssl3xjb.ashx?num=30&lottery=SHSSL");
    }

	public LotteryDrawFetchWorkerCpblm(LotteryType lotteryType){
		super(lotteryType);
	}
	
	@Override
	public LotteryDraw fetchResult(String phase) {
        return this.fetchResultDetail(phase);
    }

	@Override
	public LotteryDraw fetchResultDetail(String phase) {
        LotteryType lotteryType = this.getLotteryType();

        String fetchUrl = this.getResultDetailUrl(phase);
        if (StringUtils.isEmpty(fetchUrl)) {
            logger.error("==详细页面==抓取=={}==期号：{}==详细地址不存在，返回null", lotteryType.getName(), phase);
            return null;
        }

        Map<String, String> headerParams = new HashMap<String, String>();
        headerParams.put("Referer", "http://zoushitu.cpblm.com/");
        headerParams.put("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");

        String data = CoreFetcherUtils.URLGetWithHeaderParams(fetchUrl, headerParams, null, CharsetConstant.CHARSET_UTF8);

        if (StringUtils.isEmpty(data)) {
            logger.error("data is null or 404 Not Found, url={}", fetchUrl);
            return null;
        }

        JSONObject drawTotalObject = null;

        try {
            drawTotalObject = JSONObject.fromObject(data);
        } catch (Exception e) {
            logger.error("将开奖结果数据转换成JSON出错", e);
        }

        if (drawTotalObject == null) {
            logger.error("未取到有效数据, data={}", data);
            return null;
        }

        JSONArray drawTotalArray = null;
        try {
            drawTotalArray = drawTotalObject.getJSONArray("Rows");
        } catch (Exception e) {
            logger.error("将开奖结果数据转换成JSON出错", e);
        }

        if (drawTotalArray == null) {
            logger.error("未取到有效数据行, data={}", data);
            return null;
        }

        LotteryDraw lotteryDraw = new LotteryDraw();
        lotteryDraw.setLotteryType(lotteryType);

        // 遍历查找结果，指定phase则查找指定的彩期，未指定取最后一个为最新彩期
        for (int i = drawTotalArray.size() - 1; i >= 0; i --) {
            JSONObject drawRowObject = null;
            try {
                drawRowObject = drawTotalArray.getJSONObject(i);
            } catch (Exception e) {
                logger.error("获取开奖结果数据行出错，跳过", e);
                continue;
            }


            String fetchedPhase = StringUtils.trim(CoreJSONUtils.getString(drawRowObject, "term"));
            if (StringUtils.isNotBlank(phase)) {
                if (!phase.equals(fetchedPhase)) {
                    continue;
                }
            }

            lotteryDraw.setPhase(fetchedPhase);
            lotteryDraw.setTimeDraw(CoreDateUtils.formatDateTime(CoreJSONUtils.getDate(drawRowObject, "opentime", CoreDateUtils.DATE)));

            String fetchedResultStr = StringUtils.trim(CoreJSONUtils.getString(drawRowObject, "num"));

            char[] fetchedResultChars = fetchedResultStr.toCharArray();

            StringBuffer sb = new StringBuffer();
            for (int k = 0, kmax = fetchedResultChars.length; k < kmax; k ++) {
                sb.append(fetchedResultChars[k]);
                if (k != kmax -1) {
                    sb.append(",");
                }
            }
            lotteryDraw.setResult(sb.toString());

            if (StringUtils.isBlank(phase)) {
                break;
            }
        }

        if (lotteryDraw.getPhase() == null) {
            logger.error("未抓取到彩期数据或彩期不匹配");
            return null;
        }

        return lotteryDraw;
	}

	@Override
	protected String getResultDetailUrl(String phase) {
        LotteryType lotteryType = this.getLotteryType();

        if (!lotteryTypeMap.containsKey(lotteryType)) {
            return null;
        }

        return lotteryTypeMap.get(lotteryType);
    }

	@Override
	protected String getResultUrl(String phase) {
		return null;
	}
}
